package fr.bugtracker.commun.outils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author Laurent
 * @version 0.1
 */
public class UtilsHibernate {

	/**
	 * le session factory
	 */
	private static SessionFactory sessionFactory;
	/**
	 * la session hibernate
	 */
	public static Session session;

	static {
		try {
			Configuration cfg = new Configuration();
			cfg.configure("/hibernate.cfg.xml");

			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
			sessionFactory = cfg.buildSessionFactory(serviceRegistry);

			session = sessionFactory.openSession();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}



	/**
	 * <p><b>Accès en lecture à l'attribut sessionFactory.</b></p>
	 * @return Retourne l'attribut sessionFactory sous forme de <code>SessionFactory</code>.
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	/**
	 * Retourne la session, si la session n'existe pas, alors on l'ouvre
	 * @return {@link Session}
	 */
	public static Session getSession() {
		if (session == null || !session.isOpen()) {
			session = sessionFactory.openSession();
		}
		return session;
	}

	/**
	 * Ferme la session si elle est déjà ouverte
	 */
	public static void closeSession() {
		if (session.isOpen()) {
			session.clear();
			session.close();
		}
	}
}